package com.cershy.linyuminiserver.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;
import java.util.Optional;

public class HttpHeadersHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            // 处理HTTP握手请求
            FullHttpRequest request = (FullHttpRequest) msg;
            
            // 解析URI获取x-token参数
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
            String token = Optional.ofNullable(urlBuilder.getQuery())
                .map(k -> k.get("x-token"))
                .map(CharSequence::toString)
                .orElse("");
                
            // 存储token到channel属性
            NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token);

            // 清理URI路径
            request.setUri(urlBuilder.getPath().toString());
            
            // 获取客户端真实IP
            HttpHeaders headers = request.headers();
            String ip = headers.get("X-Real-IP");
            if (StringUtils.isEmpty(ip)) {
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();
            }
            
            // 存储IP到channel属性
            NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
            
            // 移除本处理器（仅用于握手阶段）
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(request);
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}